package com.woniu.controller;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.domain.ExtUserInfo;
import com.alipay.api.domain.ExtendParams;
import com.alipay.api.domain.GoodsDetail;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;

import com.woniu.been.entity.UserOrders;
import com.woniu.mapper.UserOrdersMapper;
import com.woniu.service.UserOrdersService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/alipay")
@CrossOrigin
public class AlipayController {

    @Autowired
    UserOrdersMapper userordersmapper;

    @Autowired
    UserOrdersService userOrdersService;
    private static  String  outTradeno;
    private static  Integer  userId;
    private  static  String  ids;
    private  static  String  courseids;
    private final AlipayClient alipayClient;
    String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCtWwC1EB6AM0eEIMYj4UyfMfp19lAz9IPuC+2Ipk8IjCcRpJKd5DkygzbNtsqmGITY6AUn4njCiAM22EBGAX5npzz85vmukj0fAbIXZpJtI9C7O+1a0qdA397gQ5EuYL0GEw0jkZA6uxZSNvA21LSM0LJb7MJPvQ2D1zM7H2lXz9mcAYWp8vpChD8zjmWIe0yrvMec8sX8LPBToTk1k6s9iF8DPlHk1gN0CWCh02g5e8Ak1XiODOkQUOsEADsI9ucM4A5Sod2ZcocdSlzjpjWZsuOwn+4Kz/Swj+FmG45SrsD3Ke3Z63U0l4oUUMVAg7AVGPwFZWD5PVqGuMyOlHd3AgMBAAECggEAJJclwhIB7htkx/3G9MHUU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rMSxmwEef8aWyMQvsdmi7ePfBkmv7x/Q7ntG+TV/YFQOS/PRyrYc/5kZ/robVKa+EyBCTeZXV8xGtG2aXo5jxf/YiFeAMu2dSclBPYcXTJAMFVDgKSwkgAlgjY";
    String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp3NUKBdI9pZj0EzSfxmwg1uw/FLyIpMPOXdA42igoD0M1/OyO5tzQ9Zs9NA7vtsRKfh3TZmj5PygkeWaiEVMJDFIjpsmWWQPX481somUaf4flBKST4tRU5FpzG3MmucPY2YZt/2oamimRZsfIkIIo1+m77PJxXaCaL3BvvBRr5KVXyBSntPkk+8CkJd6ieg8Lx61gM4szmZJ8WB7ShBBifPhV1Vs69aHftuuSRP0epNuqkgRKCEx8qB3l4BL0jzexogxBhj2Z+o34lqXwEf4Kq8ybUtxAMcdba8hAjteee3FDNE1nRpuiOREOya1j6hNItqEE3iRRcRVAw9MTUS7DQIDAQAB";  //   <-- 请填写您的支付宝公钥，例如：MIIBIjANBg... -->
    public AlipayController() {
        // 初始化AlipayClient
        this.alipayClient = new DefaultAlipayClient(
                // alipay.trade.wap.pay
                "https://openapi-sandbox.dl.alipaydev.com/gateway.do", // 沙箱环境 网关
                "9021000149652915", // 支付宝AppID
                //应用私钥
                privateKey,
                "json",
                "UTF-8",
                //支付宝公钥
                alipayPublicKey,
                "RSA2" // 签名类型
        );
    }

    @PostMapping("/order1")
    public Map<String, Object> createOrderOne(@RequestBody Map<String, Object> req) throws AlipayApiException {
        System.out.println("订单传入的参数   "+req);
        Map<String, Object> responseMap = new HashMap<>();
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());
       //     private  static  String  ids;
        //    private  static  String  courseids;
        ids = (String) req.get("ids");
        courseids = (String) req.get("courseids");
        // 构造请求参数以调用接口
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        JSONObject bizconetent = new JSONObject();
        userId = (Integer) req.get("userId");
        outTradeno = (String) req.get("TradeNo");
        bizconetent.set("out_trade_no", req.get("TradeNo"));
        bizconetent.set("total_amount", req.get("totalAmount"));
        bizconetent.set("subject",  req.get("subject"));
        bizconetent.set("product_code", req.get("product_code"));
        // 设置商户订单号 需要参数
        if(req.get("TradeNo") !=null ){
            model.setOutTradeNo((String) req.get("TradeNo"));
        }
        // 设置订单总金额 需要传参
        if(req.get("totalAmount") !=null ){
            model.setTotalAmount((String) req.get("totalAmount"));
        }
        // 设置订单标题
        if(req.get("subject") !=null ){
            model.setSubject((String) req.get("subject"));
        }
//        model.setProductCode("QUICK_WAP_WAY");
//        request.setBizContent();
        // 设置产品码
        model.setProductCode("QUICK_WAP_WAY");
//        model.setBody("CESID");
//        model.setSellerId("maijiaid");
        // 设置针对用户授权接口
//        model.setAuthToken("appopenBb64d181d0146481ab6a762c00714cC27");
        // 设置商户传入业务信息
//        model.setBusinessParams("{\"mc_create_trade_ip\":\"127.0.0.1\"}");

        // 设置公用回传参数
//        model.setPassbackParams("merchantBizType%3d3C%26merchantBizNo%3d2025010101111");

     //        设置商户的原始订单号
//        model.setMerchantOrderNo("20251008001");
        //
        String body = "ids="+ids+"courseids="+courseids+"userid="+userId;
        request.setBizContent("{\"out_trade_no\":\"" + req.get("TradeNo") + "\","
                + "\"total_amount\":\"" +  req.get("totalAmount") + "\","
                + "\"subject\":\"" +  req.get("subject") + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
//        request.setBizModel(model);
//        request.setBizContent(bizconetent.toString());

        request.setNotifyUrl("http://yeyyy.mynatapp.cc/alipay/notify");
        // 第三方代调用模式下请设置app_auth_token
        // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");

//        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "POST");
        // 如果需要返回GET请求，请使用 这里是向支付宝发送请求
         AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "GET");
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData+"-------------支付宝的api");

        if (response.isSuccess()) {
            responseMap.put("tradeNO", pageRedirectionData);
            System.out.println("调用成功");
        } else {
            responseMap.put("error", "支付宝订单创建失败");
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        return  responseMap;
    }

    @PostMapping("/checkupdate") // 轮询
    public String checkupdate(@RequestBody Map<String, Object> req) {
        // userId
        String  TradeNo= (String) req.get("TradeNo");
        // 从订单表中查询 该订单的状态
        List<UserOrders> userorders =  userOrdersService.findOrderByNumber(TradeNo);
        if(userorders.size() >0){
            return userorders.get(0).getPaymentStatus();
        }else{
            return "error";
        }
    }

    private static AlipayConfig getAlipayConfig() {
        //  <-- 请填写您的应用私钥，例如：MIIEvQIBADANB ... ... -->
        String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCtWwC1EB6AM0eEIMYj4UyfMfp19lAz9IPuC+2Ipk8IjCcRpJKd5DkygzbNtsqmGITY6AUn4njCiAM22EBGAX5npzz85vmukj0fAbIXZpJtI9C7O+1a0qdA397gQ5EuYL0GEw0jkZA6uxZSNvA21LSM0LJb7MJPvQ2D1zM7H2lXz9mcAYWp8vpChD8zjmWIe0yrvMec8sX8LPBToTk1k6s9iF8DPlHk1gN0CWCh02g5e8Ak1XiODOkQUOsEADsI9ucM4A5Sod2ZcocdSlzjpjWZsuOwn+4Kz/Swj+FmG45SrsD3Ke3Z63U0l4oUUMVAg7AVGPwFZWD5PVqGuMyOlHd3AgMBAAECggEAJJclwhIB7htkx/3G9MHUU3HQJN/1s9GzmyZHX+WCnxI+GNo83DjU3dWWVrtzcLWSLNpkZDPIO39L9mKUxnIARU6mb9cs8m0Jm6bW+Vt8Iq9BmpOemOIHzYizWXDJjxl6LHMO/ef2on7kyjuwXl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        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp3NUKBdI9pZj0EzSfxmwg1uw/FLyIpMPOXdA42igoD0M1/OyO5tzQ9Zs9NA7vtsRKfh3TZmj5PygkeWaiEVMJDFIjpsmWWQPX481somUaf4flBKST4tRU5FpzG3MmucPY2YZt/2oamimRZsfIkIIo1+m77PJxXaCaL3BvvBRr5KVXyBSntPkk+8CkJd6ieg8Lx61gM4szmZJ8WB7ShBBifPhV1Vs69aHftuuSRP0epNuqkgRKCEx8qB3l4BL0jzexogxBhj2Z+o34lqXwEf4Kq8ybUtxAMcdba8hAjteee3FDNE1nRpuiOREOya1j6hNItqEE3iRRcRVAw9MTUS7DQIDAQAB";  //   <-- 请填写您的支付宝公钥，例如：MIIBIjANBg... -->
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");  // https://openapi.alipay.com/gateway.do
        alipayConfig.setAppId("9021000149652915");  // <-- 请填写您的AppId，例如：2019091767145019 -->
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        return alipayConfig;
    }
}